<?php

/* * ************************************************* *\
 * @company		: NovaITech							  *	
 * @author		: van.vo@novaitech.com				  * 
 * @copyright	: 2012								  * 
 * ================================================== *
 * @date		: {creation_date}
 * @project		: 
 * @description	: {description}
 * 		- 
 *
  \* ************************************************** */

class Services extends MY_Controller {

    function __construct() {
        parent::__construct();
        $this->load->library(array('form_validation', 'table'));
        $this->load->helper(array('form', 'url'));
        $this->load->model('CodeGenerator_model', '', TRUE);
        $this->load_template();
    }

    function index() {
        $this->manage();
    }

    /* ------------------------------------------------------------ *\
      | - FUNC Purpose	: View list
      | - Parameters		:
      |		Name			Type		Description
      |		---------------------------------------------------
      |		N/A
      |
      | - Return			:
      |			- N/A
      \* ------------------------------------------------------------ */

    function view() {
        // Get rules from config file
        // --------------------------------------------------
        //$rules                  =   $this->form_validation->_config_rules[ 'services_add' ];
        $rules = array(array('field_id' => 'Serv_ID', 'label' => 'Serv_ID', 'control' => 'Array',), array('field_id' => 'Serv_Name', 'label' => 'Serv_Name', 'control' => 'Array',), array('field_id' => 'Serv_Name_EN', 'label' => 'Serv_Name_EN', 'control' => 'Array',), array('field_id' => 'Price', 'label' => 'Price', 'control' => 'Array',), array('field_id' => 'TienTip', 'label' => 'Tien tip', 'control' => 'Array',), array('field_id' => 'Create_Dt', 'label' => 'Create_Dt', 'control' => 'Array',),);
        $this->data['rules'] = $rules;

        // Make header
        // --------------------------------------------------
        $header = array();
        foreach ($rules as $item) {
            $header[] = $item['label'];
        }

        $this->data['header'] = $header;
        $results = $this->CodeGenerator_model->get('services', 'Serv_ID,Serv_Name,Serv_Name_EN,Price,TienTip,Create_Dt');

        $actions = array();



        // Make action Rent/Contact/Review
        // --------------------------------------------------
        for ($i = 0; $i < count($results); $i++) {
            $id = array_values($results[$i]);

            if (!empty($actions)) {
                foreach ($actions as $item) {
                    $results[$i][$item['action_name']] = anchor(base_url() .
                            'index.php/services/' . $item['action_func'] . "/" . $id[0], $item['action_name']);
                }
            }
        }

        $this->data['results'] = $results;
        $this->data['master_limited'] = explode(',', 'Serv_ID,Serv_Name,Serv_Name_EN,Price,TienTip,Create_Dt');
        $this->data['custom_action'] = $actions;

        $this->load->view('services_list', $this->data);
    }

    /* ------------------------------------------------------------ *\
      | - FUNC Purpose	: Manage list
      | - Parameters		:
      |		Name			Type		Description
      |		---------------------------------------------------
      |		N/A
      |
      | - Return			:
      |			- N/A
      \* ------------------------------------------------------------ */

    function manage() {

        //paging
        $filter = $this->input->get('filter');
        $orderby = $this->input->get('orderby');
		$start = $this->uri->segment(3);
        if (empty($filter)) {
            $filter = "Create_Dt";
            $orderby = "DESC";
        }
       
        // filter danh muc
        $sql = "select Ca_ID,Name from categories order by Name";
        $results = $this->CodeGenerator_model->custom_query($sql, "array");
        $combobox_cats[''] = "Tat ca danh muc";
        foreach ($results as $item) {
            $combobox_cats[$item['Ca_ID']] = $item['Name'];
        }
		$post = false;
        $selected_cat = $this->input->post('dm');
        if (empty($selected_cat))
            $selected_cat = $this->input->get('dm');
		else{
			$post = true;
		}
        if (empty($selected_cat))
            $selected_cat = '';
		
		$config['base_url'] = base_url() . 'services/manage/';
        if ($filter) {
            $config['suffix'] = "/?filter=$filter&orderby=$orderby&dm=$selected_cat";
            $config['first_url'] = $config['base_url'] . "0/?filter=$filter&orderby=$orderby&dm=$selected_cat";
        }	
		
		if($post){
			$start= 0;//neu la` post thi co' nghia la` phan trang se tro ve trang thai ban dau
			$config['uri_segment'] = 20;// dua page current ve 0
		}
		
        $str_dm = "";
        if (!empty($selected_cat))
            $str_dm = "and Cat_ID =$selected_cat";
        $this->data['combobox_cats'] = form_dropdown('dm', $combobox_cats, $selected_cat);
        //end
        $sql = "select Serv_ID from services where 1 $str_dm";
        $total = $this->CodeGenerator_model->custom_query($sql, "array");
        $config['total_rows'] = count($total);
        $config['per_page'] = PER_PAGE;
        $this->pagination->initialize($config);
        
        if (empty($start))
            $start = 0;
        $perpage = $config['per_page'];
        if (empty($filter))
            $str_orderby = '';
        else
            $str_orderby = "order by $filter $orderby";
        // Get rules from config file
        // --------------------------------------------------
        //$rules                  =   $this->form_validation->_config_rules[ 'services_add' ];
        $rules = array(
            array('field_id' => 'Category_Name', 'label' => 'Danh mục', 'control' => 'Array','width' => '20%', 'class' => 'first border-right', 'style' => 'border-right: solid 3px #fff;'),
            array('field_id' => 'Serv_Name', 'label' => 'Tên dịch vụ', 'control' => 'Array', 'width' => '45%', 'class' => 'border-right', 'style' => 'border-right: solid 3px #fff;'),
            array('field_id' => 'Price', 'label' => 'Giá', 'control' => 'vnd', 'class' => 'border-right', 'width' => '5%', 'style' => 'border-right: solid 3px #fff;'),
            array('field_id' => 'TienTip', 'label' => 'Tien tip', 'control' => 'vnd', 'class' => 'border-right', 'width' => '5%', 'style' => 'border-right: solid 3px #fff;'),
            array('field_id' => 'Percent_Serv', 'label' => '% dịch vụ', 'control' => 'percent', 'class' => 'border-right', 'width' => '5%', 'style' => 'border-right: solid 3px #fff;'),);


        // Make header
        // --------------------------------------------------
        $header = array();
        foreach ($rules as $k => $item) {
            $header[] = $item['label'];
            $str1 = '';
            $str2 = '';
            if ($filter == $item['field_id']) {
                if ($orderby == "DESC") {
                    $orderby = "ASC";
                    $img1 = "display: none;";
                    $img2 = "display: inline;";
                } else {
                    $orderby = "DESC";
                    $img1 = "display: inline;";
                    $img2 = "display: none;";
                }
                $url = base_url() . "services/manage/$start/?filter=$filter&orderby=$orderby&dm=$selected_cat";
                $str1 = 'onmouseout="$(\'.soimg2\').toggle()" onmouseover="$(\'.soimg2\').toggle()"';
                $str2 = '<img class="icon ic_s_asc soimg2" alt="Ascending" title="" src="' . base_url() . 'resources/images/dot.gif" style="' . $img1 . '"> <img class="icon ic_s_desc soimg2 hide" alt="Descending" title="" src="' . base_url() . 'resources/images/dot.gif" style="' . $img2 . '">';
            }
            else
                $url = base_url() . "services/manage/$start/?filter=" . $item['field_id'] . "&orderby=ASC&dm=$selected_cat";
            $rules[$k]['html'] = '<span><a title="" ' . $str1 . ' href="' . $url . '">' . $item['label'] . ' ' . $str2 . '</a></span>';
            if (isset($item['order']) && !$item['order'])
                $rules[$k]['html'] = $item['label'];
        }
        $this->data['rules'] = $rules;
        $this->data['header'] = $header;

        $sql = "select s.*, c.Name as Category_Name from services as s, categories as c where s.Cat_ID=c.Ca_ID $str_dm $str_orderby limit $start,$perpage";
        // echo $sql;
        // $results                =   $this->CodeGenerator_model->get( 'services', 'Serv_ID,Cat_ID, Time, Serv_Name,Serv_Name_EN,Price,Create_Dt' );
        $results = $this->CodeGenerator_model->custom_query($sql, "array");

        // Make action Edit/Delete
        // --------------------------------------------------
        for ($i = 0; $i < count($results); $i++) {
            $id = array_values($results[$i]);
            $results[$i]['Edit'] = anchor(base_url() . 'services/edit/' . $id[0], 'Edit');
            $results[$i]['Delete'] = anchor(
                    base_url() . 'index.php/services/delete/' . $id[0], 'Delete', array('onClick' => 'return deletechecked(\' ' . base_url() . 'services/delete/' . $id[0] . ' \')'));
        }

        $this->data['results'] = $results;
        $this->data['master_limited'] = explode(',', 'Serv_ID,Category_Name,Serv_Name,Serv_Name_EN,Time,Price,TienTip,Percent_Serv,Create_Dt');
        $this->data['action'] = array(array('id' => 'new', 'label' => 'Thêm dịch vụ', 'url' => 'index.php/services/add/',), array('id' => 'edit', 'label' => 'Edit', 'url' => 'index.php/services/edit/',), array('id' => 'delete', 'label' => 'Delete', 'url' => '',),);
        // $this->load->view( 'services_list', $this->data ); 
        $this->template->write('title', 'Spa - Danh sách dịch vụ');
        $this->template->write_view('content', 'services_list.php', $this->data);
        $this->template->render();
    }

    /* ------------------------------------------------------------ *\
      | - FUNC Purpose	: Load form add new record
      | - Parameters		:
      |		Name			Type		Description
      |		---------------------------------------------------
      |		N/A
      |
      | - Return			:
      |			- N/A
      \* ------------------------------------------------------------ */

    function add() {
        $this->data['custom_error'] = '';
        $username = "noname";
        $userid = 0;
        $Serv_ID = set_value('Serv_ID');
        if (!$Serv_ID)
            $Serv_ID = "SV_" . uniqid();
        $this->data['temp_id'] = $Serv_ID;
        $selected_cat = $this->input->post('Cat_ID');
        $categories = $this->CodeGenerator_model->get('categories', '*');
        $combobox_cats = array();
        foreach ($categories as $cat) {
            $combobox_cats[$cat['Ca_ID'] . '_' . $cat['Vip']] = $cat['Name'];
        }

        if (strpos($selected_cat, "_") !== false) {
            $selected_cat = substr($selected_cat, 0, 1);
        }

        $this->data['combobox_cats'] = form_dropdown('Cat_ID', $combobox_cats, $selected_cat, 'id="Cat_ID"');
        if (!empty($categories) && 0 < sizeof($categories)) {
            $this->data['combobox_vip_first'] = $categories[$selected_cat]['Vip'];
        } else {
            // Avoid crash system (unset variable)
            $this->data['combobox_vip_first'] = 0; // 0 mean service normal
        }
        $checked = $this->input->post('vip');
        $isVIP = 0;
        if ($checked != '') {
            $isVIP = 1;
        }
        if ($this->form_validation->run('services_add') == false) {
            $this->data['custom_error'] = ( validation_errors() ? '<div class="form_error">' . validation_errors() . '</div>' : false );
            if ($isVIP) {
                $this->data['services_vip'] = $this->input->post('services');
            } else {
                // Avoid crash system
                $this->data['services_vip'] = array();
            }
        } else {
            // Get all normal services selected
            $arrServicesSelected = $this->input->post('services');
            $data = array(
                'Serv_ID' => $Serv_ID,
                'Serv_Name' => set_value('Serv_Name'),
                'vip' => $isVIP,
                'Serv_Name_EN' => set_value('Serv_Name_EN'),
                'Time' => set_value('Time'),
                'Cat_ID' => $selected_cat,
                'Price' => set_value('Price'),
                'TienTip' => set_value('TienTip'),
                'Percent_Serv' => set_value('Percent_Serv'),
                'Create_Dt' => time(),
                'Descriptions' => set_value('Descriptions'),
            );
            $result = $this->CodeGenerator_model->add('services', $data, 'Serv_ID');
            // Add to services_vip table
            if (!empty($arrServicesSelected)) {
                foreach ($arrServicesSelected as $value) {
                    $vip_data = array(
                        'services_id' => $Serv_ID,
                        'sub_services_id' => $value
                    );
                    $this->CodeGenerator_model->add('services_vip', $vip_data);
                }
            }
            if ($result == ADD_SUCCESSFULLY) {
                redirect(base_url() . 'index.php/services/manage/');
            } else if ($result == RECORD_EXISTED) {
                $this->data['custom_error'] = '<div class="form_error"><p>A record existed.</p></div>';
            } else {
                $this->data['custom_error'] = '<div class="form_error"><p>An Error Occured.</p></div>';
            }
        }
        // $this->load->view( 'services_add', $this->data );
        /* @var $categories type */
        $categories = $this->CodeGenerator_model->get('categories', 'Ca_ID, Name, Create_Dt',array("Vip"=>0));//Vip = 0 chi lay danh muc ko fai la vip
        for ($i = 0; $i < sizeof($categories); $i++) {
            $services = $this->CodeGenerator_model->get('services', '*', array('Cat_ID' => $categories[$i]['Ca_ID'], 'vip' => 0, 'SoSuat'=>1));//SoSuat = 1 ==> ko fai phieu
            $categories[$i]['services'] = $services;
        }
        $this->data['categories'] = $categories;
        $this->template->write('title', 'Spa - Thêm dịch vụ');
        $this->template->write_view('content', 'services_add.php', $this->data);
        $this->template->render();
    }

    /* ------------------------------------------------------------ *\
      | - FUNC Purpose	: Load edit form.
      | - Parameters		:
      |		Name			Type		Description
      |		---------------------------------------------------
      |		N/A
      |
      | - Return			:
      |			- N/A
      \* ------------------------------------------------------------ */

    function edit() {
        $this->data['custom_error'] = '';
        $username = "noname";
        $userid = 0;
        $selected_cat = $this->input->post('Cat_ID');
        if ($this->form_validation->run('services_edit') == false) {
            $this->data['custom_error'] = ( validation_errors() ? '<div class="form_error">' . validation_errors() . '</div>' : false );
        } else {
            $checked = $this->input->post('vip');
            $isVIP = 0;
            if ($checked != '') {
                $isVIP = 1;
            }

            // Get all normal services selected
            $arrServicesSelected = $this->input->post('services');

            $data = array(
                'Serv_Name' => $this->input->post('Serv_Name'),
                'vip' => $isVIP,
                'Serv_Name_EN' => $this->input->post('Serv_Name_EN'),
                'Price' => $this->input->post('Price'),
                'TienTip' => $this->input->post('TienTip'),
                'Percent_Serv' => $this->input->post('Percent_Serv'),
                'Cat_ID' => $selected_cat,
                'Time' => $this->input->post('Time'),
                'Create_Dt' => time(),
                'Descriptions' => $this->input->post('Descriptions'),
            );

            $Serv_ID = $this->input->post('Serv_ID');
            $tblServices_vip = $this->CodeGenerator_model->get('services_vip', '*', array('sub_services_id' => $Serv_ID));
            if (1 == $isVIP) {
                log(sizeof($tblServices_vip));
                log(sizeof($arrServicesSelected));

                // Xoa tat ca dich vu VIP
                $this->CodeGenerator_model->delete('services_vip', 'services_id', $Serv_ID);

                // Them vao lai
                // Add to services_vip table
                foreach ($arrServicesSelected as $value) {

                    $vip_data = array(
                        'services_id' => $Serv_ID,
                        'sub_services_id' => $value
                    );
                    $this->CodeGenerator_model->add('services_vip', $vip_data);
                }
            } else {
                $this->CodeGenerator_model->delete('services_vip', 'services_id', $Serv_ID);
            }

            if ($this->CodeGenerator_model->edit('services', $data, 'Serv_ID', $this->input->post('Serv_ID')) == TRUE) {
                redirect(base_url() . 'index.php/services/manage/');
            } else {
                $this->data['custom_error'] = '<div class="form_error"><p>An Error Occured</p></div>';
            }
        }
        $result = $this->CodeGenerator_model->get('services', '*', 'Serv_ID = "' . $this->uri->segment(3) . '"', NULL, NULL, true);

        // $this->load->view( 'services_edit', $this->data );
        if (!$selected_cat) {
            $selected_cat = $result->Cat_ID;
        }
        $categories = $this->CodeGenerator_model->get('categories', '*',array("Vip"=>0));//Vip = 0 chi lay danh muc ko fai la vip
        $combobox_cats = array();
        foreach ($categories as $cat) {
            $combobox_cats[$cat['Ca_ID'] . '_' . $cat['Vip']] = $cat['Name'];
        }
        

        if (strpos($selected_cat, "_") !== false) {
            $selected_cat = substr($selected_cat, 0, 1);
        }
        
        if (!empty($categories) && 0 < sizeof($categories)) {
            $this->data['combobox_vip_first'] = $categories[$selected_cat]['Vip'];
        } else {
            // Avoid crash system (unset variable)
            $this->data['combobox_vip_first'] = 0; // 0 mean service normal
        }
        
        $selected_cat = $selected_cat . "_" . $categories[$selected_cat-1]['Vip'];
        /* get service normal, except itself */
        for ($i = 0; $i < sizeof($categories); $i++) {
            $services = $this->CodeGenerator_model->get('services', '*', array('Cat_ID' => $categories[$i]['Ca_ID'], 'vip' => 0, 'Serv_ID !=' => $this->uri->segment(3),'SoSuat'=>1));//so suat = 1 ==> khac phieu
            $categories[$i]['services'] = $services;
        }

        $this->data['services_vip'] = $this->CodeGenerator_model->get('services_vip', '*', array('services_id' => $this->uri->segment(3)));
        $this->data['categories'] = $categories;
        $this->data['result'] = $result;
        //echo $selected_cat;die;
        $this->data['combobox_cats'] = form_dropdown('Cat_ID', $combobox_cats, $selected_cat, 'id="Cat_ID"');
        
        $this->template->write('title', 'Spa - Sửa dịch vụ');
        $this->template->write_view('content', 'services_edit.php', $this->data);
        $this->template->render();
    }

    /* ------------------------------------------------------------ *\
      | - FUNC Purpose	: Delete record
      | - Parameters		:
      |		Name			Type		Description
      |		---------------------------------------------------
      |		N/A
      |
      | - Return			:
      |			- N/A
      \* ------------------------------------------------------------ */

    function delete() {
        $ID = $this->uri->segment(3);
        $this->CodeGenerator_model->delete('services', 'Serv_ID', $ID);
        $this->CodeGenerator_model->delete('services_vip', 'services_id', $ID);
        redirect(base_url() . 'index.php/services/manage/');
    }

}